package com.example.luhenchang_pdf;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.luhenchang_pdf.drag.DefaultItemTouchHelpCallback;
import com.example.luhenchang_pdf.drag.DefaultItemTouchHelper;
import com.example.luhenchang_pdf.pdfutils.PdfItextUtil;
import com.example.luhenchang_pdf.pdfutils.PdfUtils;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.rayzhang.android.rzalbum.RZAlbum;
import com.rayzhang.android.rzalbum.model.AlbumPhoto;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
    public static int PHOTO_IMAGE = 2;
    private RecyclerView pdf_recycler;
    private ArrayList<String> mList = new ArrayList<>();
    private ReleaseMsgAdapter adapter;
    private ImageButton title_iv_back;
    private TextView title_tv_center;
    private TextView title_tv_save;
    private PdfItextUtil pdfItextUtil;
    private ProgressDialog myDialog; // 保存进度框


    private static final int PDF_SAVE_START = 1;// 保存PDF文件的开始意图
    private static final int PDF_SAVE_RESULT = 2;// 保存PDF文件的结果开始意图
    private static final int PDF_SAVE_RESULTs = 3;// 保存PDF文件的结果开始意图


    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case PDF_SAVE_START:
                    if (!myDialog.isShowing())
                        myDialog.show();
                    break;

                case PDF_SAVE_RESULT:
                    if (myDialog.isShowing())
                        myDialog.dismiss();
                    Toast.makeText(Main2Activity.this, "保存成功", Toast.LENGTH_SHORT)
                            .show();
                    break;
            }
            return false;
        }
    });
    private FloatingActionButton fabutton;
    private LinearLayout visiblelin;
    private FrameLayout frameLayout;
    private boolean fabOpened=false;
    private TextView hechengTv,zhinengTv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main2);
        initView();
        initProgress();

    }

    private void initView() {
        title_iv_back = findViewById(R.id.title_iv_back);
        title_iv_back.setOnClickListener(this);
        title_tv_center = findViewById(R.id.title_tv_center);
        title_tv_center.setText("合成PDF");
        title_tv_save = findViewById(R.id.title_tv_save);
        title_tv_save.setOnClickListener(this);
        title_tv_save.setText("合成");
       // title_tv_save.setVisibility(View.VISIBLE);
        pdf_recycler = findViewById(R.id.pdf_recycler);
        visiblelin=findViewById(R.id.visibal_lin);
        frameLayout=findViewById(R.id.fl_menban);
        fabutton=findViewById(R.id.fabutton);
        hechengTv=findViewById(R.id.click_pdf1);
        zhinengTv=findViewById(R.id.click_pdf2);
        hechengTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mList.size() > 0) {
                    for (int i = 0, len = mList.size(); i < len; i++) {
                        Log.e("TAG", "onActivityResult: 222" + mList.get(i));
                    }
                    toPDF();
                    Toast.makeText(Main2Activity.this, "合成PDF", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Main2Activity.this, "没有选中图片", Toast.LENGTH_SHORT).show();
                }
                closeMemu();
            }
        });
        TextView clickshowsheet=findViewById(R.id.click_pdf);
        clickshowsheet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Main2Activity.this,LookPDFActivity.class));
                closeMemu();
            }
        });

        fabutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!fabOpened){
                    openMenu();
                }else{
                    closeMemu();
                }
            }
        });





        setRecyclerView();
    }
    public void openMenu(){
        ObjectAnimator animator=ObjectAnimator.ofFloat(fabutton,"rotation",0,-155,-155);
        animator.setDuration(500);
        animator.start();
        frameLayout.setVisibility(View.VISIBLE);
        visiblelin.setVisibility(View.VISIBLE);
        AlphaAnimation alphaAnimation=new AlphaAnimation(0,1f);
        alphaAnimation.setDuration(500);
        alphaAnimation.setFillAfter(true);
        frameLayout.startAnimation(alphaAnimation);
        visiblelin.startAnimation(alphaAnimation);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {

            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
        ObjectAnimator animator1=ObjectAnimator.ofFloat(visiblelin,"rotation",0,-15,-8,-11,0);
        animator1.setDuration(500);
        animator1.start();
        fabOpened=true;

    }
    public void closeMemu(){
        ObjectAnimator animator=ObjectAnimator.ofFloat(fabutton,"rotation",-135,20,0);
        animator.setDuration(500);
        animator.start();
        AlphaAnimation alphaAnimation=new AlphaAnimation(1f,0);
        alphaAnimation.setDuration(500);
        frameLayout.startAnimation(alphaAnimation);
        visiblelin.startAnimation(alphaAnimation);
        frameLayout.setVisibility(View.GONE);
        visiblelin.setVisibility(View.GONE);
        fabOpened=false;
    }

    /**
     * 初始化识别进度框
     */
    private void initProgress() {
        myDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        myDialog.setIndeterminateDrawable(getResources().getDrawable(
                R.drawable.progress_ocr));
        myDialog.setMessage("正在保存PDF文件...");
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.setCancelable(false);
    }

    private void setRecyclerView() {
        if (mList != null) {
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
            pdf_recycler.setLayoutManager(gridLayoutManager);
            adapter = new ReleaseMsgAdapter(Main2Activity.this, mList);
            pdf_recycler.setAdapter(adapter);
            DefaultItemTouchHelper itemTouchHelper = new DefaultItemTouchHelper(new DefaultItemTouchHelpCallback.OnItemTouchCallbackListener() {

                @Override
                public boolean onMove(int srcPosition, int targetPosition) {
                    // 更换数据源中的数据Item的位置
                    Collections.swap(mList, srcPosition, targetPosition);
                    // 更新UI中的Item的位置，主要是给用户看到交互效果
                    adapter.notifyItemMoved(srcPosition, targetPosition);
                    return true;
                }
            });
            itemTouchHelper.attachToRecyclerView(pdf_recycler);
            itemTouchHelper.setDragEnable(true);
            itemTouchHelper.setSwipeEnable(false);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_iv_back:
                finish();
                break;
            case R.id.title_tv_save:

                if (mList.size() > 0) {
                    for (int i = 0, len = mList.size(); i < len; i++) {
                        Log.e("TAG", "onActivityResult: 222" + mList.get(i));
                    }
                    toPDF();
                    Toast.makeText(this, "合成PDF", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "没有选中图片", Toast.LENGTH_SHORT).show();
                }
                //再这里进行pdf的合成
                //图片数据路劲有了代表bitmap已经ok了

                break;
        }
    }

    public void toPDF() {
        File file = new File(PdfUtils.ADDRESS);
        if (!file.exists())
            file.mkdirs();
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        final String pdf_address = PdfUtils.ADDRESS + File.separator + "PDF_"
                + sdf.format(date) + ".pdf";
        handler.sendEmptyMessage(PDF_SAVE_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    pdfItextUtil = new PdfItextUtil(pdf_address);
                    //判断是否有图片没有土司提示选择图片
                    //如果有进行合成
                    if (mList.size() > 0) {
                        for (int i = 0; i < mList.size(); i++) {
                            Bitmap bitmap=BitmapFactory.decodeStream(new FileInputStream(mList.get(i)));
                            //这里当然可以输入文字和标题之类的。我们项目里面是只有图片所以。只需要.addImageToPdfCenterH();当然这里的图片在pdf中的放置可以通过设置的。看工具类
                            pdfItextUtil.addTitleToPdf("我是标题"+i).addImageToPdfCenterH(mList.get(i), PageSize.A4.getWidth() - 20, PageSize.A4.getWidth() /bitmap.getWidth() * bitmap.getHeight()).addTextToPdf("这是pdf文件的内容，我这里进行了集成这个Demo，希望可以帮助项目中遇到pdf以及文字合成，我尽自己所能,希望编程路上可以帮助到出来匝道的萌新们");
                        }

                    } else {
                        Toast.makeText(Main2Activity.this, "请选选择图片", Toast.LENGTH_SHORT).show();
                    }

                    /* pdfItextUtil = new PdfItextUtil(pdf_address)
                            .addTitleToPdf("哈哈哈哈哈哈")
                            .addTextToPdf("小时一宗大都但是你下u狗的两个垃圾啊的佛教是浪费家里睡大觉分类数据分类将军澳隧道连接法兰圣诞节佛山警方拉数据")
                            .addImageToPdfCenterH(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + "aa.jpg", PageSize.A4.getWidth()-20,PageSize.A4.getWidth()/bitmap1.getWidth()*bitmap1.getHeight())
                            .addTextToPdf("真滴都是无语打来电话了发几份简历垃圾死了就大了就")
                            .addImageToPdfCenterH(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyPdf" + File.separator + "bb.jpg",  PageSize.A4.getWidth()-20,PageSize.A4.getWidth()/bitmap2.getWidth()*bitmap2.getHeight())
                            .addTextToPdf("笑死宝宝补偿钱");*/
                    pdfItextUtil.close();
                    handler.sendEmptyMessage(PDF_SAVE_RESULT);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (pdfItextUtil != null) {
                        pdfItextUtil.close();
                    }
                }
            }
        }).start();
    }

    /**
     * 这里的“我爱你我的家我的家我的天堂”可以是你想要输入的字体。转为pdf
     * 识别结果转为PDF文件
     */
    private void turnToPdf() {
        if ("我爱你我的家我的家我的天堂".equals("")
                || "我爱你我的家我的家我的天堂" =="") {
            Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
            return;
        }
        File file = new File(PdfUtils.ADDRESS);
        if (!file.exists())
            file.mkdirs();
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        final String pdf_address = PdfUtils.ADDRESS + File.separator + "PDF_"
                + sdf.format(date) + ".pdf";
        handler.sendEmptyMessage(PDF_SAVE_START);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Document doc = new Document();// 创建一个document对象
                FileOutputStream fos;
                try {
                    fos = new FileOutputStream(pdf_address); // pdf_address为Pdf文件保存到sd卡的路径
                    PdfWriter.getInstance(doc, fos);
                    doc.open();
                    doc.setPageCount(1);
                    doc.add(new Paragraph("我爱你我的家我的家我的天堂",
                            setChineseFont())); // result为保存的字符串
                    // ,setChineseFont()为pdf字体
                    // 一定要记得关闭document对象
                    doc.close();
                    fos.flush();
                    fos.close();
                    handler.sendEmptyMessage(PDF_SAVE_RESULT);
                } catch (FileNotFoundException e1) {
                    e1.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 设置PDF字体(较为耗时)
     */
    public Font setChineseFont() {
        BaseFont bf;
        Font fontChinese = null;
        try {
            // STSong-Light : Adobe的字体
            // UniGB-UCS2-H : pdf 字体
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                    BaseFont.NOT_EMBEDDED);
            fontChinese = new Font(bf, 12, Font.NORMAL);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fontChinese;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 2:
                    List<AlbumPhoto> paths = RZAlbum.parseResult(data);
                    Log.d("RZAlbum", "GetPath:" + paths);
                    for (int i = 0, len = paths.size(); i < len; i++) {
                        Log.e("TAG", "onActivityResult: 111" + paths.get(i).getPhotoPath());
                        mList.add(paths.get(i).getPhotoPath());
                    }
                    setRecyclerView();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
